package hibernate;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import controller.Index;
import pojo.Comment;
import pojo.Deals;
import pojo.Orderdetail;
import pojo.Orders;
import pojo.Orderstatus;
import pojo.Products;
import pojo.User;
import pojo.Userroles;
import pojo.Uservoteproduct;
import pojo.Wishlist;
import dao.AdminDAO;
@Repository("AdminDAO")
public class HibernateAdminDAO implements AdminDAO {

	private SessionFactory sessionFactory;
	private static final Logger logger = Logger.getLogger(HibernateAdminDAO.class);

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	//deal manage
	@Transactional
	public boolean adddeal(Deals deal) {
		Session session = sessionFactory.getCurrentSession();
        try
        {
            session.save(deal);
            logger.info("save deals to database complete");
            return true;
        }
        catch(HibernateException e)
        {
            System.err.print(e);
            logger.error("Save deals to database error, this is it :",e);;
            return false;
        }
	}
	@Transactional
	public List<Deals> getdeallist()
	{
		Query query = sessionFactory.getCurrentSession().createQuery("from Deals");
		return query.list();
	}
	@Transactional
	public List<Products> getproductlistdealid(int dealid)
	{
		String hql = "from Products d where d.deals="+dealid;
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		return query.list();
		
	}
	@Transactional
	public Userroles getusrolebyrole(String roles)
	{
		String hql = "from Userroles u where u.roles ='"+roles+"'";

		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		return (Userroles)query.uniqueResult();
	}
	@Transactional
	public boolean updateProduct(int productid)
	{
		String hql = "update Products set deals = null where productid ="+ productid;
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		try
		{
			query.executeUpdate();
			logger.info("Update Product to database done");
			return true;
		}
		catch(Exception e)
		{
			logger.error("Can not update product with errors, this is it :",e);
			e.printStackTrace();
		}
		return false;
	}
	@Transactional
	public Deals getdealbyid(int dealid)
	{
		String hql = "from Deals d where d.dealid ="+ dealid;
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		return (Deals)query.uniqueResult();

	}
	@Transactional
	public boolean removedeal(Deals deal) {
		Session session = sessionFactory.getCurrentSession();
        try
        {
            session.delete(deal);
            logger.info("Delete deals from database completed");
            return true;
        }
        catch(HibernateException e)
        {
        	logger.error("Can not delete deals from database,error, this is it :",e);
            return false;
        }
	}
	@Transactional
	public boolean removedeal(int dealid) {
		Session session = sessionFactory.getCurrentSession();
        try
        {
        	String hql ="from Deals d where d.dealid ="+dealid;
        	Query query = session.createQuery(hql);
        	Deals deal = (Deals) query.uniqueResult();
            session.delete(deal);
            logger.info("Delete deal from database by id completed");
            return true;
        }
        catch(HibernateException e)
        {
        	logger.error("Error, this is it :",e);
            return false;
        }
	}
	@Transactional
	public boolean updatedeal(Deals deal) {
		Session session = sessionFactory.getCurrentSession();
        try
        {
            session.update(deal);
            logger.info("update deal to database completed");
            return true;
        }
        catch(HibernateException e)
        {
        	logger.error("Update deals to database, this is error :",e);
            return false;
        }
	}
	//--------------------------------------------------------------------
	// user manage
	@Transactional
	public List<User> getuserlist()
	{
		Query query = sessionFactory.getCurrentSession().createQuery("from User");
		return query.list();
	}
	@Transactional
	public boolean deleterelationuser(int memberid)
	{
		try
		{
		String hql = "update Orders set memberid = null where memberid ="+memberid;
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.executeUpdate();
		String hql2 = "update Wishlist set memberid = null where memberid ="+memberid;
		query = sessionFactory.getCurrentSession().createQuery(hql2);
		query.executeUpdate();
		hql ="from Comment where user.memberid ="+ memberid;
		query = sessionFactory.getCurrentSession().createQuery(hql);
		
		List<Comment> cm = query.list();
		Session session = sessionFactory.getCurrentSession();
		for(int i = 0; i< cm.size();i++)
		{
			session.delete(cm.get(i));
		}
		
		logger.info("Delete relation before delete user completed");
		return true;
		}
		catch(HibernateException e)
		{
			logger.error("Delete relationship before delete user Error, this is it :",e);
			e.printStackTrace();
		}
		return false;
		
	}
	
	
	@Transactional
	public User getUserbyid(int memberid)
	{
		Session session= sessionFactory.getCurrentSession();
        User user = null;
        String hql = "from User s where s.memberid ="+memberid;
        Query query = session.createQuery(hql);
      
        return (User)query.uniqueResult();
	}
	@Transactional
	public boolean addUser(User user) {
		Session session = sessionFactory.getCurrentSession();
        try
        {
            session.save(user);
            logger.info("Save new user to database completed");
            return true;
        }
        catch(HibernateException e)
        {
        	logger.error("Save new user to database got Error, this is it :",e);
            return false;
        }
	}
	@Transactional
	public boolean removeUser(User user) {
		Session session = sessionFactory.getCurrentSession();
        try
        {
        	
            session.delete(user);
            logger.info("Delete user from database done");
            return true;
        }
        catch(DataIntegrityViolationException e)
        {
        	logger.error("delete user from database got Error, this is it :",e);
            return false;
        }
    
	}
	@Transactional
	public boolean updateUser(User user) {
		Session session = sessionFactory.getCurrentSession();
        try
        {
            session.update(user);
            logger.info("Update user to database completed");
            return true;
        }
        catch(HibernateException e)
        {
        	logger.error("update user to database got Error, this is it :",e);
            return false;
        }
	}
	
	//Order manage
	@Transactional
	public List<Orders> getOrderlist()
	{
		Query query = sessionFactory.getCurrentSession().createQuery("from Orders");
		return query.list();	
	}
	@Transactional
	public List<Orderstatus> getOrderstatusList()
	{
		Query query = sessionFactory.getCurrentSession().createQuery("from Orderstatus");
		return query.list();	
	}
	@Transactional
	public boolean deleteorderdetail(int orderid)
	{
		String hql = "from Orderdetail o where o.orders.orderid ="+orderid;
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		List<Orderdetail> ordtl = query.list();
		Session session = sessionFactory.getCurrentSession();
		try
		{
		for(int i = 0;i < ordtl.size();i++)
			session.delete(ordtl.get(i));
			logger.info("Delete relation before delete Order completed");
		return true;
		}
		catch(Exception e)
		{
			logger.error("Delete relation before delete Order got Error, this is it :",e);
			e.printStackTrace();
			return false;
		}
		
		
	}
	@Transactional
	public Orders getorderbyid(int orderid)
	{
		Session session= sessionFactory.getCurrentSession();
        User user = null;
        String hql = "from Orders s where s.orderid ="+orderid;
        Query query = session.createQuery(hql);
      
        return (Orders)query.uniqueResult();
	}
	@Transactional
	public boolean updatestatus(int statusid,int orderid)
	{
		String hql = "update Orders set statusid ="+statusid+"where orderid = "+orderid;
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		try
		{
		
		query.executeUpdate();
		logger.info("Update order status completed");
		return true;
		}
		catch(Exception e)
		{
			logger.error("Update order status got Error, this is it :",e);
			e.printStackTrace();
		}
		return false;
	}
	@Transactional
	public Orders getOrderbyid(int orderid)
	{
		Session session= sessionFactory.getCurrentSession();
        User user = null;
        String hql = "from Orders s where s.orderid ="+orderid;
        Query query = session.createQuery(hql);
      
        return (Orders)query.uniqueResult();
		
	}
	@Transactional
	public boolean addorder(Orders order) {
		Session session = sessionFactory.getCurrentSession();
        try
        {
 
            session.save(order);
            logger.info("Save new order to database completed");
            return true;
        }
        catch(HibernateException e)
        {
        	logger.error("Save new order to database got Error, this is it :",e);
            return false;
        }
	}
	@Transactional
	public boolean removeorder(Orders order) {
		Session session = sessionFactory.getCurrentSession();
        try
        {
        	
            session.delete(order);
            logger.info("Delete order from database completed");
            return true;
        }
        catch(HibernateException e)
        {
        	logger.error("Delete order from database got Error, this is it :",e);
            return false;
        }
	}
	@Transactional
	public boolean updateorder(Orders order) {
		Session session = sessionFactory.getCurrentSession();
        try
        {
        	
            session.update(order);
            logger.info("Update order to database completed");
            return true;
        }
        catch(HibernateException e)
        {
        	logger.error("Update order to database got Error, this is it :",e);
        	return false;
        }
	}
	//Product Manage
	@Transactional
	public boolean deleterelationproduct(int productid)
	{
		try
		{
		String hql = "from Orderdetail o where o.products.productid ="+productid;
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		List<Orderdetail> ordtl = query.list();
		Session session = sessionFactory.getCurrentSession();
		for(int i = 0;i < ordtl.size();i++)
			session.delete(ordtl.get(i));
		hql = "from Wishlist w where w.products.productid ="+productid;
		query = sessionFactory.getCurrentSession().createQuery(hql);
		List<Wishlist> wishlist = query.list();
		for(int i = 0;i < wishlist.size();i++)
			session.delete(wishlist.get(i));
		hql = "from Uservoteproduct u where u.products.productid ="+productid;
		query = sessionFactory.getCurrentSession().createQuery(hql);
		List<Uservoteproduct> us = query.list();
		for(int i = 0;i < us.size();i++)
			session.delete(us.get(i));
		hql = "from Comment cm where cm.products.productid ="+productid;
		query = sessionFactory.getCurrentSession().createQuery(hql);
		List<Comment> cmt = query.list();
		for(int i = 0;i < cmt.size();i++)
			session.delete(cmt.get(i));
		logger.info("Delete relation of product completed");
		return true;
		}
		catch(Exception e)
		{
			logger.error("Delete relation of product got Error, this is it :",e);
			e.printStackTrace();
			return false;
		}
		
	}
	@Transactional
	public boolean removeproductbyid(int productid)
	{
		String hql = "from Products d where d.productid ="+ productid;
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		Products d = (Products)query.uniqueResult();
		Session session = sessionFactory.getCurrentSession();
		try
		{
			logger.info("Delete product from database by id completed");
			session.delete(d);
			return true;
		}
		catch(Exception e)
		{
			logger.error("Can not delete product because of Error, this is it :",e);
			return false;
		}
	}
	@Transactional
	public boolean updateProduct(int productid,String productname,float price,String model,String description,int warranty,String image1,String image2,float tax,int procatalogid,int dealid,int brandid,int conditionid,String specifications,String features,int quantity)
	{
		String hql = "update Products set productname ='"+productname+"',price ="+price+",model ='"+model+"',description='"+description+"',warranty="+warranty+",image1='"+image1+"',image2='"+image2+"',productcatalog="+procatalogid+",brand="+brandid+",conditions="+conditionid+",quantity="+quantity;
		if(dealid == -1)
			hql += ",deals = null";
		else hql += ",deals ="+dealid;
		if(specifications.equals(""))
			hql+=",specifications= null";
		else hql += ",specifications ='"+specifications+"'";
		if(features.equals(""))
			hql+=",features=null";
		else
			hql+=",features='"+features+"'";
		hql+= " where productid ="+productid;
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		try
		{
		query.executeUpdate();
		logger.info("Update product to database done");
		return true;
		}
		catch(Exception e)
		{
			logger.error("Update product to database got Error, this is it :",e);
			e.printStackTrace();
		}
		return false;
	}
	@Transactional
	public boolean addProduct(Products prd)
	{
		Session session = sessionFactory.getCurrentSession();
        try
        {
            session.save(prd);
            logger.info("Save new product to database done");
            return true;
        }
        catch(HibernateException e)
        {
        	logger.error("Save new product to database got Error, this is it :",e);
            return false;
        }
	}

	

}
